﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WpfAdvControls.StatusPanel;

namespace TfsComLib.TfsConnection.View
{
    /// <summary>
    ///     Interaction logic for TfsProperties.xaml
    /// </summary>
    public partial class TfsProperties : UserControl
    {
        private TfsConnectionData connectionData;

        public TfsProperties()
        {
            InitializeComponent();
        }

        public TfsProperties(TfsConnectionData connectionData)
        {
            InitializeComponent();
            SetBinding(connectionData);
        }

        /// <summary>
        ///     Set bindings
        /// </summary>
        /// <param name="connectionData">TfsConnectionData that should be binded to UI</param>
        public void SetBinding(TfsConnectionData connectionData)
        {
            if (connectionData == null)
                throw new Exception("TfsProperties.xaml.cs: Object TfsConnectionData is null");
            this.connectionData = connectionData;
            url.DataContext = connectionData;
            url.SetBinding(TextBox.TextProperty, "Uri");
            collection.DataContext = connectionData;
            collection.SetBinding(TextBox.TextProperty, "CollectionName");
            statusBox.DataContext = connectionData;
            statusBox.SetBinding(ThreeStatusBox.StatusProperty,
                new Binding("Status") {Converter = new StatusConnectedConverter()});
            statusBox.SetBinding(ThreeStatusBox.StatusTextProperty, new Binding("ErrorMessage"));
            connectButton.DataContext = connectionData;
        }

        private void connectClick(object sender, RoutedEventArgs e)
        {
            connectionData.TestConnect();
        }

        private void changeConnection_Click(object sender, RoutedEventArgs e)
        {
            connectionData.Reconnect();
        }
    }

    internal class StatusConnectedConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var status = (TfsConnectStatus) value;
            switch (status)
            {
                case TfsConnectStatus.Connected:
                    return ThreeStatusEnum.Success;
                case TfsConnectStatus.ConnectError:
                case TfsConnectStatus.Error:
                    return ThreeStatusEnum.Error;
                case TfsConnectStatus.Disconnected:
                    return ThreeStatusEnum.Unknown;
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }

        #endregion
    }
}